//
//  MoviePlayerView.m
//  Eyes（Stroyboard）
//
//  Created by lanou on 16/3/1.
//  Copyright © 2016年 雨天记忆. All rights reserved.
//

#import "MoviePlayerView.h"
#import <AVFoundation/AVFoundation.h>
#import <MediaPlayer/MediaPlayer.h>
// 枚举
typedef NS_ENUM(NSInteger, Movement)
{
    HorizontailMovement,
    VerticalMovement
    
};


@interface MoviePlayerView()
{
    float _nowTime; // 平移总和的值
    Movement _movement; // 枚举值 判断水平移动或者垂直移动
}

@property (weak, nonatomic) IBOutlet UIView *volumView;
@property (weak, nonatomic) IBOutlet UISlider *volum;
@property (weak, nonatomic) IBOutlet UIButton *backButton;
@property (weak, nonatomic) IBOutlet UIButton *playButton;
@property (weak, nonatomic) IBOutlet UILabel *timeLabel;
@property (weak, nonatomic) IBOutlet UIView *downView;
@property (weak, nonatomic) IBOutlet UISlider *prograssSlider;
@property (weak, nonatomic) IBOutlet UILabel *endLabel;
@property (weak, nonatomic) IBOutlet UILabel *beganLabel;

@property(nonatomic, strong)UISlider *volumeSlider;
@property(nonatomic, strong)AVPlayer *player;
@property(nonatomic, strong)NSTimer *timer;

@end

@implementation MoviePlayerView

// 必须写
- (void)dealloc{
    _delegate = nil;
}


-(instancetype)initWithFrame:(CGRect)frame URL:(NSURL *)url
{
    self = [super initWithFrame:frame];
    if (self) {
        self = [[NSBundle mainBundle]loadNibNamed:@"MoviePlayerView" owner:nil options:nil][0];
        self.frame = [UIScreen mainScreen].bounds;
        // 去除滑块
        [self.volum setThumbImage:[UIImage imageNamed:@"nil.png"] forState:UIControlStateNormal];
        [self.prograssSlider setThumbImage:[UIImage imageNamed:@"nil.png"]forState:UIControlStateNormal];        // 旋转slider
        self.volumView.transform = CGAffineTransformMakeRotation(-M_PI_2);
        
        AVPlayerItem *item = [AVPlayerItem playerItemWithURL:url];
        self.player = [AVPlayer playerWithPlayerItem:item];
        AVPlayerLayer *layer = [AVPlayerLayer playerLayerWithPlayer:_player];
        layer.frame = frame;
        [self.layer insertSublayer:layer atIndex:0];
        [self.player play];
        
        // 添加手势 控制视图的出现和消失
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]init];
        [tap addTarget:self action:@selector(showAction)];
        [self addGestureRecognizer:tap];
        
        // 初始化定时器
        self.timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(timerAction:) userInfo:nil repeats:YES];

        // 添加一个用来快进快退的平移手势
        UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(panAction:)];
        [self addGestureRecognizer:pan];
        
        // 声音控件
        MPVolumeView *volumeView = [[MPVolumeView alloc]initWithFrame:CGRectMake(-100, 0, 10, 10)];
        // 接收系统控制音量
        self.volumeSlider = volumeView.subviews[0];
        // 第一次对系统的音量赋值
        self.volum.value = self.volumeSlider.value;
        [self addSubview:_volumView];
        
    }
    return self;
}

// 添加触摸出现消失的手势
- (void)showAction
{
    self.playButton.hidden = !self.playButton.hidden;
    self.backButton.hidden = !self.backButton.hidden;
    self.downView.hidden = !self.downView.hidden;
    self.volumView.hidden = self.playButton.hidden;

    // 先取消一次消失视图方法 然后再添加 保证只有一个视图消失的方法在走
    [self noShow];
    
}

// 出现后隔5秒消失
- (void)noShow
{
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(dismiss) object:nil];
    [self performSelector:@selector(dismiss) withObject:nil afterDelay:5];
}

// 消失的方法
- (void)dismiss
{
    self.playButton.hidden = YES;
    self.backButton.hidden = YES;
    self.downView.hidden = YES;
    self.volumView.hidden = YES;
}

// 点击播放按钮切换图片 暂停、播放
- (IBAction)playClick:(UIButton *)sender
{
    if (sender.selected)
    {
        [self play];
    }
    else
    {
        [self pause];
    }
    sender.selected = !sender.selected;
}

// 播放
- (void)play
{
    [self.player play];
}

// 暂停
- (void)pause
{
    [self.player pause];
}
//*******************************************************************************
// 定时器
- (void)timerAction:(NSTimer *)timer
{
    if (!self.prograssSlider.highlighted)
    {
        //AVPlayer获取进度
        long long seconds = self.player.currentTime.value / self.player.currentTime.timescale;
        float m = seconds / 60;
        int s = seconds % 60;
        self.beganLabel.text = [NSString stringWithFormat:@"%02d:%02d",(int)m,s];
        // 下面的滑块也跟着滑动
        self.prograssSlider.value = seconds;
    }
}

#pragma mark --- 滑块滑行的执行方法 ---
- (IBAction)valueChanged:(UISlider *)sender forEvent:(UIEvent *)event
{
    [self noShow];
    // 获取手指
    UITouch *touch = [[event allTouches]anyObject];
    switch (touch.phase) {
        case UITouchPhaseBegan:
        {
            // 开始触摸
            break;
        }
        case UITouchPhaseMoved:
        {
            // 移动
            float m = sender.value / 60;
            int s = (int)sender.value % 60;
            self.timeLabel.text = [NSString stringWithFormat:@"%02d:%02d",(int)m,s];
            break;
        }
        case UITouchPhaseEnded:
        {
            // 结束
            self.currentTime = sender.value;
            break;
        }
        default:
            break;
    }
}

#pragma mark --- 设置endLabel和滑块的最大值
- (void)setModel:(MicroMainModel *)model
{
    _model = model;
    int m = model.duration / 60;
    int s = model.duration % 60;
    self.endLabel.text = [NSString stringWithFormat:@"%02d:%02d",m,s];
    // 给滑块时间的最大值
    self.prograssSlider.maximumValue = model.duration;
    //NSLog(@"%d",model.duration);
}



#pragma mark --- 修改进度set方法 ---
- (void)setCurrentTime:(float)currentTime
{
    //_currentTime = currentTime;
    CMTime newTime = self.player.currentTime;
    newTime.value = newTime.timescale * currentTime;
    // AVPlayer进度跳转的办法
    [self.player seekToTime:newTime];
}



#pragma mark --- 平移手势的执行方法 ---
- (void)panAction:(UIPanGestureRecognizer *)pan
{
    CGPoint point = [pan velocityInView:self];
    //NSLog(@"x ========== %f,y =========%f",point.x,point.y);
    NSString *style = @">>";
    switch (pan.state) {
        case UIGestureRecognizerStateBegan:
        {
            // 开始平移 通过绝对值判断是水平移动还是垂直移动
            // 通过绝对值判断
            float x = fabs(point.x);
            float y = fabs(point.y);
            if (x > y) // 水平移动
            {
                _movement = HorizontailMovement;
                self.timeLabel.hidden = NO;
                // 显示播放的进度 当前播放到的一个位置
                self.timeLabel.text = [self timeStr:self.currentTime style:style];
                // 在开始的时候 给nowTime赋一个原始值
                _nowTime = self.currentTime;
            }
            else // 垂直移动
            {
                _movement = VerticalMovement;
                self.volumView.hidden = NO;
            }
            break;
        }
        case UIGestureRecognizerStateChanged:// 移动
        {
            switch (_movement) {
                case HorizontailMovement:
                {
                    [self horizontailMovement:point.x style:style];
                     break;
                }
                case VerticalMovement:
                {
                    [self verticalMovement:point.y];
                    break;
                }
                default:
                    break;
            }
            break;
        }
        case UIGestureRecognizerStateEnded:// 平移结束
        {
            if (_movement == HorizontailMovement) {
                // 隐藏进度label
                self.timeLabel.hidden = YES;
                // 结束的时候 进行跳转
                self.currentTime = _nowTime;
                // _nowTime置空，便于下一次使用
                _nowTime = 0;
            }
            else
            {
                self.volumView.hidden = YES;
            }
            break;
        }
        default:
            break;
    }
    
}

#pragma mark --- 垂直移动的方法 ---
- (void)verticalMovement:(float)value
{
    // 更改系统的声音
    self.volumeSlider.value = self.volumeSlider.value - value/10000 ;
    self.volum.value = self.volumeSlider.value;
}

#pragma mark --- 水平移动的方法 ---
- (void)horizontailMovement:(float)x style:(NSString *)style
{
    _nowTime = _nowTime + (x / 50);
    // 限制nowTime的范围
    if ( _nowTime < 0) {
        _nowTime = 0;
    }
    else if (_nowTime > self.model.duration)
    {
        _nowTime = self.model.duration;
    }
    if (x < 0) {
        style = @"<<";
    }
    else
    {
        style = @">>";
    }
    self.timeLabel.text = [self timeStr:_nowTime style:style];
}




#pragma mark --- 返回00：00--00:00时间格式的方法
- (NSString *)timeStr:(float)time style:(NSString *)style
{
    int m = time / 60;
    int s = (int)time % 60;
    int M = self.model.duration / 60;
    int S = self.model.duration % 60;
    return [NSString stringWithFormat:@"%@ %02d:%02d / %02d:%02d",style,m,s,M,S];
    
}

#pragma mark --- get方法 返回当前的播放进度 ---
- (float)currentTime
{
    return self.player.currentTime.value / self.player.currentTime.timescale;
}


#pragma mark --- 返回 ---
- (IBAction)backAction:(UIButton *)sender
{
    if ([self.delegate respondsToSelector:@selector(back)]) {
        // 关闭timer 防止返回之后还有声音的问题
        [self.timer invalidate];
        self.timer = nil;
        [self pause];
        
        
        [self.delegate back];
    }
}


@end














